<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Websocket通用测试页面</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="//cdn.staticfile.org/layui/2.6.8/css/layui.css"  media="all">
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <style media="screen">
        body{
            padding: 16px;
        }
        .left-box{
            padding: 16px;
        }
        .msg-box{
            border: 1px solid #ddd;
            border-radius: 3px;
        }
        .msg-top{
            width: 100%;
            height: 40px;
            background-color: #eee;
            border-bottom: 1px solid #ddd;
            padding: 8px;
            color: #888;
        }
        .msg-notes{
            padding: 8px;
            font-size: 14px;

            height: 600px;
            overflow: scroll;
        }
        .color-s{
            color:blue;
        }
        .color-c{
            color: green;
        }
        p{
            margin-bottom: 3px;
        }
        #status{
            float: right;
        }
    </style>
</head>
<body>
    <div class="layui-containers">
        <div class="layui-row">
            <div class="layui-col-md3 left-box">
                <div class="form-group">
                    <label for="wsurl">socket地址:</label>
                    <input type="text" class="form-control" id="wsurl" placeholder="ws://127.0.0.1:2345">
                </div>

                <div class="form-group">
                    <div class="btn-group">
                        <button type="button" id="connect" data="0" class="btn btn-success">连接</button>
                    </div>
                    <span id="status" class="badge badge-pill badge-warning">未连接</span>
                </div>

                <div class="form-group">
                    <label for="nick">昵称:</label>
                    <input type="text" class="form-control" id="nick" placeholder="托搭李天王">
                </div>

                <div class="form-group">
                    <label for="content">信息输入框:</label>
                    <textarea class="form-control" rows="5" id="content"></textarea>
                </div>

                <button class="btn btn-primary" id="send">发送</button>
                <button class="btn btn-info" id="clear">清空消息</button>
            </div>
            <div class="layui-col-md9 left-box">
                <div class="msg-box">
                    <div class="msg-top">Websocket通用测试页面</div>
                    <div class="msg-notes"></div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="//cdn.staticfile.org/layui/2.6.8/layui.js" charset="utf-8"></script>
<script>
var rid = Math.floor(Math.random()*100);
var nicks = [];
var lib = ["秦始皇","齐桓公","晋文公","楚庄王","越王勾践","宋襄公","秦穆公","晋悼公","唐太宗","唐玄宗","赵匡胤","项羽","赵高","吕雉","樊哙"];//设置总颜色
var nick = lib[Math.floor(Math.random() * lib.length)];

var tool = {};
// sessionStorage存储数据
tool.cache = function(key,value=null){
    if(value==null){
        // 读取数据
        value = sessionStorage.getItem(key);
        return JSON.parse(value);
    }else{
        // 保存数据
        sessionStorage.setItem(key,JSON.stringify(value));
        return true;
    }
}
var socket_url = "";
var ws;
layui.use(['form'], function(){
    var form = layui.form,$=layui.jquery
    ,layer = layui.layer;
    let time =new Date();

    var cachews = tool.cache("ws");
    if(cachews && cachews.url){
        $("#wsurl").val(cachews.url);
    }else{
        tool.cache("ws",{ url : "ws://127.0.0.1:2345" });
    }

    $("#nick").val(nick);

    $("#connect").on("click",function(){
        if($(this).attr("data")==1){
            $(this).text("连接");
            $(this).removeClass("btn-secondary").addClass("btn-success");
            ws.close();
            $(this).attr("data",0);
            $("#status").text("已断开").removeClass("badge-success").addClass("badge-warning");
        }else{
            socket_url = $("#wsurl").val();
            if(socket_url.length<5){
                layer.alert("连接地址不正确",{icon:2});
            }else{
                tool.cache("ws",{ url : socket_url });
                // 连接中。。。
                $(this).attr("data",1);
                $(this).text("断开");
                $(this).removeClass("btn-success").addClass("btn-secondary");
                $("#status").text("已连接").removeClass("badge-warning").addClass("badge-success");
                ws = new WebSocket(socket_url);
                ws.onopen = function() {
                    let time =new Date();
                    $(".msg-notes").append('<span class="color-s">系统消息 '+time.toLocaleString()+'</span><p>连接服务器成功。</p>');
                };
                ws.onmessage = function(e) {
                    let msg = JSON.parse(e.data);
                    let time =new Date();
                    if(msg && msg.name && msg.content){
                        $(".msg-notes").append('<span class="color-s">'+msg.name+"&nbsp;&nbsp;"+time.toLocaleString()+'</span><p>'+msg.content+'</p>');
                    }else if(msg.recently){
						$.each(msg.recently,function(index,item){
							var item09 = JSON.parse(item);
							$(".msg-notes").append('<span class="color-s">'+item09.name+"&nbsp;&nbsp;"+time.toLocaleString()+'</span><p>'+item09.content+'</p>');
						});
                    }else{
                        $(".msg-notes").append('<span class="color-s">系统消息&nbsp;&nbsp;'+time.toLocaleString()+'</span><p>'+e.data+'</p>');
                    }
                };
                ws.onclose = function()
                {
                    let time =new Date();
                    $(".msg-notes").append('<span class="color-s">系统消息 '+time.toLocaleString()+'</span><p>连接已断开。</p>');
                    $("#connect").text("连接");
                    $("#status").text("已断开").removeClass("badge-success").addClass("badge-warning");
                    $("#connect").removeClass("btn-secondary").addClass("btn-success");
                    $("#connect").attr("data",0);
                };
            }
        }
    })

    // 发送消息
    $("#send").on("click",function(){
        var content = $.trim($("#content").val());
        var mynick = $.trim($("#nick").val());
        var status = $("#connect").attr("data");
        if(content && mynick && status==1){
            var param = {};
            param.rid = rid;
            param.content = content;
            param.name = $("#nick").val();
            ws.send(JSON.stringify(param));
            let time =new Date();
            $(".msg-notes").append('<span class="color-c">发送消息 '+time.toLocaleString()+'</span><p>'+content+'</p>');
        }else{
            layer.msg("昵称和消息必须填写且在线",{offset:'50px'});
        }
    })

    // 清除信息
    $("#clear").on("click",function(){
        $(".msg-notes").empty();
    })
});
</script>
</html>
